<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="课程主题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 创建课程
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
    >
      <el-table-column label="封面图" align="center" width="100">
        <template #default="scope">
          <div class="course-image-wrapper" @click="imagePreview(scope.row.coverImage)">
            <el-image
              :src="scope.row.coverImage || ''"
              fit="contain"
              class="course-cover-image"
            >
              <template #error>
                <div class="image-error">
                  <Icon icon="ep:picture" style="font-size: 20px;" />
                </div>
              </template>
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="课程主题" min-width="200" show-overflow-tooltip />
      <el-table-column prop="categoryPathName" label="所属分类" width="180" show-overflow-tooltip />

      <el-table-column prop="teacher" label="主讲人" width="100" />
      <el-table-column prop="lessons" label="课时" width="80" align="center" />
      <el-table-column prop="price" label="售价" width="80" align="center">
        <template #default="scope">
          ¥ {{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="views" label="观看次数" width="100" align="center" />
      <el-table-column prop="createTime" label="创建时间" width="150" align="center" />
      <el-table-column label="操作" align="center" width="220" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleEdit(scope.row.id)"
          >
            信息编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-if="total > 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 弹窗 -->
  <CourseForm ref="courseFormRef" @success="getList" />
</template>

<script lang="ts" setup>
import { Icon } from '@/components/Icon'
import CourseForm from './CourseForm.vue'
import * as CourseApi from '@/api/course/info'
import { CourseInfoVO } from '@/api/course/info'
import { createImageViewer } from '@/components/ImageViewer'
import { formatDate } from '@/utils/formatTime'

defineOptions({ name: 'CourseList' })

const router = useRouter()

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 总条数
const list = ref<CourseInfoVO[]>([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  title: undefined
})
const queryFormRef = ref() // 搜索的表单

/** 查询课程列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await CourseApi.getCourseInfoPage(queryParams)
    list.value = res.list.map((item: CourseInfoVO) => ({
      ...item,
      id: item.id,
      coverImage: item.picUrl,
      title: item.title,
      categoryPathName: item.categoryPathName || '-',
      teacher: item.speaker,
      lessons: `共${item.classHourse || 0}节`,
      price: (item.price || 0) / 100, // 分转元
      sales: item.sales || 0,
      views: `${item.viewTimes || 0}次`,
      createTime: item.createTime ? formatDate(new Date(item.createTime)) : '-'
    }))
    total.value = res.total
  } catch (error) {
    console.error('获取课程列表失败', error)
    message.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const courseFormRef = ref()
const openForm = (type: string, id?: number) => {
  courseFormRef.value.open(type, id)
}

/** 编辑课程信息 */
const handleEdit = (id: number) => {
  router.push(`/course/detail/${id}`)
}

/** 图片预览 */
const imagePreview = (imgUrl: string) => {
  if (!imgUrl) return
  createImageViewer({
    urlList: [imgUrl],
    zIndex: 9999999
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 调用删除API
    await CourseApi.deleteCourseInfo(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('删除课程失败', error)
    message.error('删除课程失败')
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
.image-error {
  width: 80px;
  height: 60px;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.course-image-wrapper {
  width: 80px;
  height: 60px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin: 0 auto;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.course-cover-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
</style>
